﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Diagnostics;

namespace PMCT
{
    public partial class FormMain : Form
    {
        public string curFilename;
        public ConfigRoot curRoot;

        public FormMain()
        {
            InitializeComponent();
            SelectConfig(".\\default.xml");

            //if (File.Exists(".\\Skin\\MacOS.ssk"))
            //{
            //    skinEngine1.SkinFile = ".\\Skin\\MacOS.ssk";
            //    skinEngine1.Active = true;
            //}
        }

        private void SelectConfig(string path)
        {
            if (File.Exists(path) == true)
            {
                XmlSerializer serializer = new XmlSerializer(typeof(ConfigRoot));
                TextReader reader = new StreamReader(path);
                curRoot = (ConfigRoot)serializer.Deserialize(reader);
                reader.Close();
            }
            else
            {
                curRoot = new ConfigRoot("1.0", "空配置");
            }
            curFilename = path;

            DoRefresh();
        }

        private void ShowToolTip()
        {
            toolStripStatusLabel1.Text = "正在使用 " + curRoot.name + " (" + curRoot.version + ") 配置...";
        }

        public void DoRefresh()
        {
            // 清空配置列表和过程列表，并在提示栏中显示当前配置
            {
                treeView1.Nodes.Clear();
                listView1.Items.Clear();
                ShowToolTip();
            }

            // 显示配置列表
            {
                foreach (Dimension d in curRoot.listDimension)
                {
                    TreeNode tn = treeView1.Nodes.Add(d.name);
                    foreach (DimensionItem di in d.list)
                    {
                        tn.Nodes.Add(di.name);
                    }
                }
            }

            // 显示过程列表
            {
                // 1. 添加列
                listView1.Columns.Clear();
                listView1.HeaderStyle = ColumnHeaderStyle.Nonclickable;

                ColumnHeader ch1 = new ColumnHeader();
                ch1.Text = "名称";
                ch1.Width = 120;
                listView1.Columns.Add(ch1);

                foreach (Dimension d in curRoot.listDimension)
                {
                    ColumnHeader ch = new ColumnHeader();
                    ch.Text = d.name;
                    ch.Width = 100;
                    listView1.Columns.Add(ch);
                }

                listView1.BeginUpdate();

                ListViewItem lvi;
                ListViewItem.ListViewSubItem lvsi;

                foreach (Item item in curRoot.listItem)
                {
                    lvi = new ListViewItem();
                    lvi.Text = item.name;

                    // 添加维度
                    foreach (Dimension d in curRoot.listDimension)
                    {
                        List<int> all = new List<int>();
                        bool found = FindMatchAllGuid(d.list, item.dimension, all);

                        if (found == false)
                        {
                            lvsi = new ListViewItem.ListViewSubItem();
                            lvsi.Text = "无";
                            lvi.SubItems.Add(lvsi);
                        }
                        else
                        {
                            string str = "";
                            bool isFirst = true;
                            foreach (int i in all)
                            {
                                if (!isFirst)
                                    str += ", ";
                                str += d.list[i].name;
                                isFirst = false;
                            }
                            lvsi = new ListViewItem.ListViewSubItem();
                            lvsi.Text = str;
                            lvi.SubItems.Add(lvsi);
                        }
                    }

                    listView1.Items.Add(lvi);
                }

                listView1.EndUpdate();
            }
        }

        public static bool FindMatchAllGuid(List<DimensionItem> listDimensionItem, List<Guid> listGuid, List<int> all)
        {
            bool found = false;
            int idx = 0;

            if (all == null)
                return false;

            foreach (DimensionItem di in listDimensionItem)
            {
                int rtn = listGuid.FindIndex(delegate(Guid g) { return g == di.guid; });
                if (rtn != -1)
                {
                    all.Add(idx);
                    found = true;
                }
                idx++;
            }
            return found;
        }

        private int FindMatchGuid(List<DimensionItem> listDimensionItem, List<Guid> listGuid)
        {
            int idx = 0;
            foreach (DimensionItem di in listDimensionItem)
            {
                int rtn = listGuid.FindIndex(delegate(Guid g) { return g == di.guid; });
                if (rtn != -1)
                    return idx;
                idx++;
            }
            return idx;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ConfigDimension cd = new ConfigDimension();
            cd.curRoot = (ConfigRoot)curRoot.Clone();
            DialogResult dr = cd.ShowDialog();
            if (dr == DialogResult.OK)
            {
                curRoot = (ConfigRoot)cd.curRoot.Clone();
                DoRefresh();
            }
        }

        private void saveToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (curFilename == null)
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*";
                DialogResult dr= sfd.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    curFilename = Path.GetFileName(sfd.FileName);
                }
                else
                    return;
            }

            DoSaveSerialize();
        }

        private void DoSaveSerialize()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(ConfigRoot));
            TextWriter writer = new StreamWriter(curFilename);
            serializer.Serialize(writer, curRoot);
            writer.Close();
        }

        private void configMenuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            button1_Click(sender, e);
        }

        private void mgmtLibToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MgmtLib f = new MgmtLib();
            f.curRoot = curRoot;
            f.ShowDialog();
        }

        private void view3DFlowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string fn = "ITFlow.vsd";
            string path = Application.StartupPath + Path.DirectorySeparatorChar + fn;
            if (File.Exists(path) == true)
            {
                ProcessStartInfo psi = new ProcessStartInfo(path);
                psi.UseShellExecute = true; // u need this
                psi.ErrorDialog = true; // and this which launch the OpenWith dialog
                Process.Start(psi);
            }
            else
                MessageBox.Show("文件:" + fn + " 不存在！", "错误");
        }

        private void addMenuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ItemForm f = new ItemForm();
            f.curRoot = (ConfigRoot)curRoot.Clone();
            f.curItem = new Item("空");
            if (f.ShowDialog() == DialogResult.OK)
            {
                curRoot.listItem.Add(f.curItem);
                DoRefresh();
            }
        }

        private void modifyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ItemForm f = new ItemForm();
            f.curRoot = (ConfigRoot)curRoot.Clone();
            if (listView1.SelectedItems.Count == 0)
                return;

            int idx = listView1.SelectedItems[0].Index;
            f.curItem = (Item)curRoot.listItem[idx].Clone();
            if (f.ShowDialog() == DialogResult.OK)
            {
                curRoot.listItem[idx] = (Item)f.curItem.Clone();
                DoRefresh();
            }
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 0)
                return;

            int idx = listView1.SelectedItems[0].Index;
            Item item = curRoot.listItem[idx];
            DialogResult result = MessageBox.Show("是否确定要删除该过程？",
                "删除过程:" + item.name,
                MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                MessageBoxDefaultButton.Button2);
            if (result == DialogResult.Yes)
            {
                curRoot.listItem.RemoveAt(idx);
                DoRefresh();
            }
        }

        private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            modifyToolStripMenuItem_Click(sender, e);
        }

        private void listView1_AfterLabelEdit(object sender, LabelEditEventArgs e)
        {
            if (e.Label == null || e.Label == "")
                e.CancelEdit = true;
            else
            {
                int idx = e.Item;
                curRoot.listItem[idx].name = e.Label;
            }
        }

        private void statusStrip1_DoubleClick(object sender, EventArgs e)
        {
            NameVersion nv = new NameVersion(curRoot.name, curRoot.version);
            DialogResult dr = nv.ShowDialog();
            if (dr == DialogResult.OK)
            {
                curRoot.name = nv.name;
                curRoot.version = nv.version;
                ShowToolTip();
            }
        }

        private void newToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            SelectConfig(null);
        }

        private void openToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*";
                ofd.Title = "选择配置文件";
                ofd.Multiselect = false;
                DialogResult dr = ofd.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    SelectConfig(ofd.SafeFileName);
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("打开文件异常: " + ex.Message);
            }
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            if (listView1.SelectedItems.Count == 0)
            {
                modifyToolStripMenuItem.Enabled = false;
                deleteToolStripMenuItem.Enabled = false;
            }
            else
            {
                modifyToolStripMenuItem.Enabled = true;
                deleteToolStripMenuItem.Enabled = true;
            }
        }

        private void flowPreview_Click(object sender, EventArgs e)
        {
            ViewGantt f = new ViewGantt();
            f.curRoot = curRoot;
            f.ShowDialog();
        }

        private void viewFlowMenuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            flowPreview_Click(sender, e);
        }

        private void optionsToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Options f = new Options();
            DialogResult dr = f.ShowDialog();
            if (dr == DialogResult.OK)
            {
                if (f.skinFilename == "")
                    skinEngine1.Active = false;
                else
                {
                    skinEngine1.SkinFile = f.skinFilename;
                    skinEngine1.Active = true;
                }
            }
            System.Diagnostics.Debug.WriteLine("SkinEngine SN:" + skinEngine1.SerialNumber);
        }

        private void findSmartToolStripMenuItem_Click(object sender, EventArgs e)
        {
            InputBox ib = new InputBox();
            DialogResult dr = ib.ShowDialog();
            if (dr == DialogResult.OK)
            {
                if (ib.inputText != null && ib.inputText != "")
                {
                    ViewGantt f = new ViewGantt();
                    f.curRoot = curRoot;

                    ViewGantt.SmartFind(curRoot, ib.inputText, f.selectedItems);
                    if (f.selectedItems.Count != 0)
                    {
                        f.ShowDialog();
                    }
                    else
                    {
                        System.Windows.Forms.MessageBox.Show("无任何过程与指定字符串相关联！");
                    }
                }
            }

        }

        private void saveAsToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Title = "另存为";
            sfd.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*";
            DialogResult dr = sfd.ShowDialog();
            if (dr == DialogResult.OK)
            {
                curFilename = Path.GetFileName(sfd.FileName);
                DoSaveSerialize();
            }
        }

        private void aboutToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            string path = Path.GetDirectoryName(Application.ExecutablePath)
                + Path.DirectorySeparatorChar + "Manual.chm";
            Help.ShowHelp(this, path);
        }
    }
}
